from rest_framework import serializers
from rest_framework.generics import ListAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAdminUser

from apps.goods.models import SKU
from apps.meiduo_admin.utils import CurPagination
from apps.orders.models import OrderInfo, OrderGoods


class SimpleOrderInfoSerializer(serializers.ModelSerializer):
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = OrderInfo
        fields = ['create_time', 'order_id']
        read_only_fields = ['create_time', 'order_id']


class OrderSKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['name', 'default_image']


class OrderGoodsSerializer(serializers.ModelSerializer):
    sku = OrderSKUSerializer(read_only=True)

    class Meta:
        model = OrderGoods
        fields = ['count', 'price', 'sku']


class OrderInfoSerializer(serializers.ModelSerializer):
    skus = OrderGoodsSerializer(read_only=True, many=True)
    user = serializers.StringRelatedField(read_only=True)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')

    class Meta:
        model = OrderInfo
        fields = ['create_time', 'order_id', 'user', 'address_id', 'total_count', 'total_amount', 'freight', 'pay_method', 'status', 'skus']
        read_only_fields = ['order_id', 'user', 'address_id', 'total_count', 'total_amount', 'freight', 'pay_method']


class OrderListView(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = SimpleOrderInfoSerializer
    pagination_class = CurPagination

    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')
        if keyword:
            return OrderInfo.objects.filter(order_id__contains=keyword).order_by('-create_time').values('create_time', 'order_id')
        return OrderInfo.objects.order_by('-create_time').values('create_time', 'order_id')


class OrderView(RetrieveAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = OrderInfoSerializer

    def get_queryset(self):
        order_id = self.kwargs.get('pk')
        return OrderInfo.objects.filter(order_id=order_id)


class OrderStatusView(UpdateAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = OrderInfoSerializer

    def get_queryset(self):
        order_id = self.kwargs.get('pk')
        return OrderInfo.objects.filter(order_id=order_id)
